<template>
  <div class="ai-chat-view">
    <!-- 页面标题 -->
    <div class="chat-header">
      <el-button type="primary" size="small" @click="goBack">返回</el-button>
      <h1>AI智能解题助手</h1>
      <div class="header-actions">
        <el-button type="default" size="small" @click="clearChat">清空对话</el-button>
      </div>
    </div>

    <!-- 聊天内容区域 -->
    <div class="chat-container">
      <!-- 聊天消息列表 -->
      <div class="chat-messages" ref="chatMessagesRef">
        <div v-for="message in chatMessages" :key="message.id" class="message-item" :class="message.role">
          <div class="message-avatar">
            <div v-if="message.role === 'user'" class="user-avatar">
              <el-icon><User /></el-icon>
            </div>
            <div v-else class="ai-avatar">
              <el-icon><User /></el-icon>
            </div>
          </div>
          <div class="message-content">
            <!-- 用户消息 -->
            <div v-if="message.role === 'user'" class="user-message">
              <div v-if="message.imageUrl" class="message-image">
                <img :src="message.imageUrl" alt="题目图片" @click="previewImage(message.imageUrl)">
              </div>
              <div v-if="message.text" class="message-text">
                <p>{{ message.text }}</p>
              </div>
            </div>
            <!-- AI消息 -->
            <div v-else class="ai-message">
              <div v-if="message.isTyping" class="typing-message">
                <div class="streaming-message" v-html="message.text.replace(/\n/g, '<br>')"></div>
                <div class="typing-cursor">|</div>
              </div>
              <div v-else class="static-message" v-html="formatMarkdown(message.text)"></div>
        </div>
          </div>
        </div>
        
        <!-- 加载指示器 -->
        <div v-if="isAnalyzing" class="message-item ai">
          <div class="message-avatar">
            <div class="ai-avatar">
              <el-icon><User /></el-icon>
            </div>
          </div>
          <div class="message-content">
            <div class="ai-message">
              <div class="loading-message">
                <el-icon class="is-loading"><Loading /></el-icon>
                <span>AI正在思考中...</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="chat-input">
        <div class="input-toolbar">
          <el-button type="primary" size="small" @click="triggerFileInput" :disabled="isAnalyzing">
            <UploadFilled /> 上传图片
          </el-button>
          <el-button type="default" size="small" @click="initiateCamera" :disabled="isAnalyzing">
            <Camera /> 拍照
          </el-button>
          <input
            ref="fileInputRef"
            type="file"
            accept="image/*"
            style="display: none"
            @change="handleFileUpload"
          />
        </div>
        <div class="input-area">
          <el-input
            v-model="inputText"
            type="textarea"
            :rows="3"
            placeholder="请输入您的问题，或上传题目图片..."
            :disabled="isAnalyzing"
            @keydown.enter.prevent="sendMessage"
            class="message-input"
          />
          <el-button 
            type="primary" 
            @click="sendMessage" 
            :disabled="!canSend"
            :loading="isAnalyzing"
            class="send-button"
          >
            发送
          </el-button>
        </div>
      </div>
    </div>

    <!-- 相机模态框 -->
    <el-dialog v-model="showCameraModal" title="拍照识别题目" width="80%" :fullscreen="isMobile">
      <div class="camera-modal-content">
        <div ref="cameraContainer" class="camera-feed-container">
          <video ref="videoElement" autoplay playsinline></video>
        </div>
        <canvas ref="canvasElement" style="display: none;"></canvas>
      </div>
      <template #footer>
        <el-button @click="closeCamera">取消</el-button>
        <el-button type="primary" @click="capturePhoto">拍照识别</el-button>
      </template>
    </el-dialog>

    <!-- 图片预览 -->
    <el-dialog v-model="showImagePreview" title="题目图片预览" width="90%">
      <img :src="previewImageUrl" alt="题目图片" class="preview-image">
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { UploadFilled, Camera, Loading, User } from '@element-plus/icons-vue';
import { aiSolverApi, AiSolverRequest } from '@/api/ai-solver';
import { useAiSolverStore } from '@/store/ai-solver';

// 路由
const router = useRouter();

// AI解题存储
const aiSolverStore = useAiSolverStore();

// 响应式数据
const fileInputRef = ref<HTMLInputElement | null>(null);
const videoElement = ref<HTMLVideoElement | null>(null);
const canvasElement = ref<HTMLCanvasElement | null>(null);
const cameraContainer = ref<HTMLDivElement | null>(null);
const chatMessagesRef = ref<HTMLDivElement | null>(null);

// 页面状态
const isMobile = ref(false);
const isAnalyzing = ref(false);
const showCameraModal = ref(false);
const showImagePreview = ref(false);

// 聊天消息
interface ChatMessage {
  id: string;
  role: 'user' | 'ai';
  text: string;
  imageUrl?: string;
  timestamp: Date;
  isTyping?: boolean;
}

const chatMessages = ref<ChatMessage[]>([]);
const inputText = ref('');

// 计算属性
const canSend = computed(() => {
  return (inputText.value.trim() || pendingImage.value) && !isAnalyzing.value;
});

// 待发送的图片
const pendingImage = ref<string>('');

// 图片预览
const previewImageUrl = ref<string>('');

// 返回上一页
const goBack = () => {
  router.back();
};

// 清空聊天
const clearChat = () => {
  chatMessages.value = [];
  inputText.value = '';
  pendingImage.value = '';
  ElMessage.success('对话已清空');
};

// 触发文件上传
const triggerFileInput = () => {
  fileInputRef.value?.click();
};

// 处理文件上传
const handleFileUpload = (event: Event) => {
  const input = event.target as HTMLInputElement;
  if (input.files && input.files[0]) {
    const file = input.files[0];
    
    // 检查文件类型
    if (!file.type.startsWith('image/')) {
      ElMessage.error('请上传图片文件');
      return;
    }

    // 检查文件大小（10MB限制）
    if (file.size > 10 * 1024 * 1024) {
      ElMessage.error('图片大小不能超过10MB');
      return;
    }

    // 读取图片文件
    const reader = new FileReader();
    reader.onload = (e) => {
      pendingImage.value = e.target?.result as string;
      ElMessage.success('图片已选择，可以发送消息');
    };
    reader.readAsDataURL(file);
  }
};

// 初始化相机
const initiateCamera = async () => {
  // 适配移动端
  checkIfMobile();
  showCameraModal.value = true;
  
  try {
    // 等待模态框渲染完成后再初始化相机
    setTimeout(async () => {
      if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        const stream = await navigator.mediaDevices.getUserMedia({
          video: {
            facingMode: 'environment' // 优先使用后置摄像头
          }
        });
        
        if (videoElement.value && cameraContainer.value) {
          videoElement.value.srcObject = stream;
          // 设置视频尺寸以适应容器
          const setVideoDimensions = () => {
            if (videoElement.value) {
              videoElement.value.style.width = '100%';
              videoElement.value.style.height = 'auto';
            }
          };
          
          videoElement.value.onloadedmetadata = setVideoDimensions;
          window.addEventListener('resize', setVideoDimensions);
        }
      }
    }, 300);
  } catch (error) {
    ElMessage.error('无法访问摄像头，请确保已授予相机权限');
    console.error('Camera error:', error);
    showCameraModal.value = false;
  }
};

// 关闭相机
const closeCamera = () => {
  if (videoElement.value && videoElement.value.srcObject) {
    const stream = videoElement.value.srcObject as MediaStream;
    const tracks = stream.getTracks();
    tracks.forEach(track => track.stop());
  }
  showCameraModal.value = false;
};

// 拍照识别
const capturePhoto = () => {
  if (videoElement.value && canvasElement.value) {
    const canvas = canvasElement.value;
    const video = videoElement.value;
    
    // 设置canvas尺寸与视频一致
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    
    // 绘制当前视频帧到canvas
    const ctx = canvas.getContext('2d');
    if (ctx) {
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      
      // 获取图片数据URL
      const imageUrl = canvas.toDataURL('image/jpeg');
      pendingImage.value = imageUrl;
      
      ElMessage.success('拍照成功，可以发送消息');
      closeCamera();
    }
  }
};

// 发送消息
const sendMessage = async () => {
  if (!canSend.value) return;
  
  const messageText = inputText.value.trim();
  const messageImage = pendingImage.value;
  
  if (!messageText && !messageImage) return;
  
  // 添加用户消息
  const userMessage: ChatMessage = {
    id: `user_${Date.now()}`,
    role: 'user',
    text: messageText || '发送了一张图片',
    imageUrl: messageImage,
    timestamp: new Date()
  };
  
  chatMessages.value.push(userMessage);
  
  // 清空输入
  inputText.value = '';
  pendingImage.value = '';
  
  // 滚动到底部
  await nextTick();
  scrollToBottom();
  
  // 发送到AI
  await sendToAI(messageText, messageImage);
};

// 发送到AI
const sendToAI = async (text: string, imageUrl?: string) => {
  isAnalyzing.value = true;
  
  try {
    let stream: ReadableStream<Uint8Array>;
    
    if (imageUrl) {
      console.log('🖼️ 开始处理图片解题');
      console.log('图片URL类型:', imageUrl.startsWith('data:') ? 'base64' : 'URL');
      console.log('图片URL长度:', imageUrl.length);
      
      // 图片解题 - 处理base64图片
      const formData = new FormData();
      formData.append('question', text || '请分析这张图片中的题目');
      formData.append('questionType', '图像识别');
      formData.append('userId', '1');
      
      try {
        // 将base64图片转换为Blob
        if (imageUrl.startsWith('data:')) {
          console.log('📷 处理base64图片');
          const base64Data = imageUrl.split(',')[1];
          console.log('base64数据长度:', base64Data.length);
          
          const byteCharacters = atob(base64Data);
          const byteNumbers = new Array(byteCharacters.length);
          for (let i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
          }
          const byteArray = new Uint8Array(byteNumbers);
          
          // 根据MIME类型确定文件扩展名
          let mimeType = 'image/jpeg';
          let fileName = 'question.jpg';
          if (imageUrl.includes('data:image/png')) {
            mimeType = 'image/png';
            fileName = 'question.png';
          } else if (imageUrl.includes('data:image/gif')) {
            mimeType = 'image/gif';
            fileName = 'question.gif';
          } else if (imageUrl.includes('data:image/webp')) {
            mimeType = 'image/webp';
            fileName = 'question.webp';
          }
          
          const blob = new Blob([byteArray], { type: mimeType });
          console.log('✅ Blob创建成功，大小:', blob.size, '字节，类型:', mimeType);
          formData.append('image', blob, fileName);
        } else {
          console.log('🌐 处理URL图片');
          const imageResponse = await fetch(imageUrl);
          if (!imageResponse.ok) {
            throw new Error(`图片获取失败: ${imageResponse.status} ${imageResponse.statusText}`);
          }
          const blob = await imageResponse.blob();
          console.log('✅ URL图片Blob创建成功，大小:', blob.size, '字节，类型:', blob.type);
          formData.append('image', blob, 'question.jpg');
        }
        
        console.log('📤 发送图片解题请求（使用完整流程）');
        stream = await aiSolverApi.processFileComplete(formData);
        console.log('✅ 完整文件处理流程请求发送成功');
        
      } catch (error) {
        console.error('❌ 图片处理失败:', error);
        const errorMessage = error instanceof Error ? error.message : String(error);
        throw new Error('图片处理失败: ' + errorMessage);
      }
    } else {
      // 文本解题 - 确保传递正确的参数结构
      const requestData: AiSolverRequest = {
        question: text,
        questionType: 'auto',
        userId: 1
      };
      
      console.log('发送AI文本解题请求:', requestData);
      stream = await aiSolverApi.solveQuestionStream(requestData);
    }
    
    // 创建AI消息
    const aiMessage: ChatMessage = {
      id: `ai_${Date.now()}`,
      role: 'ai',
      text: '',
      timestamp: new Date(),
      isTyping: true
    };
    
    chatMessages.value.push(aiMessage);
    await nextTick();
    scrollToBottom();
    
    // 处理流式响应
    await handleStreamingResponse(stream, aiMessage.id);
    
  } catch (error) {
    console.error('AI解析错误:', error);
    
    // 获取更详细的错误信息
    let errorMessage = '抱歉，AI解析出现了问题，请稍后重试。';
    if (error instanceof Error) {
      if (error.message.includes('HTTP error! status: 500')) {
        errorMessage = '服务器内部错误，请稍后重试。';
      } else if (error.message.includes('HTTP error! status: 404')) {
        errorMessage = 'AI服务暂时不可用，请稍后重试。';
      } else if (error.message.includes('HTTP error! status: 503')) {
        errorMessage = 'AI服务暂时不可用，请稍后重试。';
      } else if (error.message.includes('Failed to fetch')) {
        errorMessage = '网络连接失败，请检查网络连接后重试。';
      } else if (error.message.includes('AI解析失败')) {
        errorMessage = error.message;
      } else {
        errorMessage = `AI解析失败：${error.message}`;
      }
    }
    
    ElMessage.error(errorMessage);
    
    // 添加错误消息
    const errorChatMessage: ChatMessage = {
      id: `error_${Date.now()}`,
      role: 'ai',
      text: errorMessage,
      timestamp: new Date()
    };
    
    chatMessages.value.push(errorChatMessage);
    await nextTick();
    scrollToBottom();
  } finally {
    isAnalyzing.value = false;
  }
};

// 处理流式响应
const handleStreamingResponse = async (stream: ReadableStream<Uint8Array>, messageId: string) => {
  console.log('=== 开始处理流式响应 ===');
  console.log('消息ID:', messageId);
  
  const reader = stream.getReader();
  const decoder = new TextDecoder();
  let fullText = '';
  let buffer = '';
  
  try {
    while (true) {
      const { done, value } = await reader.read();
      
      console.log('读取数据块:', { done, valueLength: value?.length });
      
      if (done) {
        console.log('流式响应结束');
        break;
      }
      
      const chunk = decoder.decode(value, { stream: true });
      console.log('解码后的数据块:', JSON.stringify(chunk));
      
      buffer += chunk;
      console.log('当前缓冲区:', JSON.stringify(buffer));
      
      // 处理SSE格式的数据
      const lines = buffer.split('\n');
      buffer = lines.pop() || ''; // 保留最后一个不完整的行
      
      console.log('处理行数:', lines.length);
      
      for (const line of lines) {
        console.log('处理行:', JSON.stringify(line));
        console.log('原始SSE行内容:', line);
        
        if (line.trim() === '') {
          console.log('跳过空行');
          continue;
        }
        
        if (line.startsWith('data:')) {
          const data = line.startsWith('data: ') ? line.substring(6) : line.substring(5);
          console.log('提取的数据:', JSON.stringify(data));
          
          if (data === '[DONE]') {
            console.log('收到结束标记');
            break;
          }
          
          // 直接作为文本处理，不尝试解析JSON
          if (data.trim()) {
            fullText += data;
            console.log('更新完整文本:', fullText);
            console.log('当前完整文本长度:', fullText.length);
            
            // 更新AI消息内容 - 在流式传输中只处理基本换行
            const message = chatMessages.value.find(m => m.id === messageId);
            if (message) {
              message.text = fullText;
              console.log('消息已更新:', message.text);
              console.log('消息文本长度:', message.text.length);
            } else {
              console.error('未找到消息ID:', messageId);
            }
            
            // 滚动到底部
            await nextTick();
            scrollToBottom();
          }
        } else if (line.startsWith('event: ')) {
          const eventType = line.substring(7).trim();
          console.log('收到事件:', eventType);
          
          if (eventType === 'complete') {
            console.log('收到完成事件');
            break;
          } else if (eventType === 'error') {
            console.log('收到错误事件');
            // 读取下一行的错误数据
            const { done: errorDone, value: errorValue } = await reader.read();
            if (!errorDone) {
              const errorChunk = decoder.decode(errorValue, { stream: true });
              console.error('AI解析错误:', errorChunk);
              throw new Error(errorChunk);
            }
            break;
          } else if (eventType === 'status') {
            console.log('收到状态事件');
            // 读取下一行的状态数据
            const { done: statusDone, value: statusValue } = await reader.read();
            if (!statusDone) {
              const statusChunk = decoder.decode(statusValue, { stream: true });
              console.log('处理状态:', statusChunk);
              
              // 更新AI消息显示状态信息
              const message = chatMessages.value.find(m => m.id === messageId);
              if (message) {
                message.text = statusChunk;
                await nextTick();
                scrollToBottom();
              }
            }
          }
        }
      }
    }
    
    // 处理缓冲区中剩余的数据
    if (buffer.trim()) {
      console.log('处理缓冲区剩余数据:', JSON.stringify(buffer));
      const lines = buffer.split('\n');
      for (const line of lines) {
        if (line.trim() === '') continue;
        console.log('原始SSE行:', line);
        
        if (line.startsWith('data:')) {
          const data = line.startsWith('data: ') ? line.substring(6) : line.substring(5);
          if (data && data !== '[DONE]') {
            fullText += data;
            console.log('缓冲区处理 - 更新完整文本:', fullText);
            console.log('缓冲区处理 - 当前完整文本长度:', fullText.length);
            
            const message = chatMessages.value.find(m => m.id === messageId);
            if (message) {
              message.text = fullText;
              console.log('缓冲区处理 - 消息已更新:', message.text);
            } else {
              console.error('缓冲区处理 - 未找到消息ID:', messageId);
            }
          }
        }
      }
    }
    
    console.log('=== 流式响应处理完成 ===');
    console.log('最终文本长度:', fullText.length);
    console.log('最终文本内容:', fullText);
    
    // 清理和规范化最终文本
    const cleanedText = cleanStreamingText(fullText);
    console.log('清理后的文本:', cleanedText);
    
    // 确保最终文本被正确设置到消息对象
    const message = chatMessages.value.find(m => m.id === messageId);
    if (message) {
      message.text = cleanedText;
      console.log('=== 最终消息更新 ===');
      console.log('消息ID:', messageId);
      console.log('设置的消息文本:', message.text);
      console.log('消息文本长度:', message.text.length);
    } else {
      console.error('未找到消息ID:', messageId);
    }
    
  } finally {
    reader.releaseLock();
    
    // 完成打字效果
    const message = chatMessages.value.find(m => m.id === messageId);
    if (message) {
      message.isTyping = false;
      console.log('打字效果完成');
    }
  }
};


// 清理流式文本
const cleanStreamingText = (text: string) => {
  if (!text) return '';
  
  // 移除多余的空白字符
  let cleaned = text.trim();
  
  // 移除流式传输过程中产生的大量不完整Markdown标记
  // 1. 移除连续的**字符（这些通常是流式传输产生的）
  cleaned = cleaned.replace(/\*{2,}/g, '');
  
  // 2. 移除开头和结尾的单个*字符
  cleaned = cleaned.replace(/^\*+/, ''); // 移除开头的*
  cleaned = cleaned.replace(/\*+$/, ''); // 移除结尾的*
  
  // 3. 移除文本中间的孤立*字符（前后都有非*字符的单个*）
  cleaned = cleaned.replace(/(?<!\*)\*(?!\*)/g, '');
  
  // 规范化换行符
  cleaned = cleaned.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
  
  // 移除多余的空行
  cleaned = cleaned.replace(/\n{3,}/g, '\n\n');
  
  return cleaned;
};

// 格式化Markdown文本
const formatMarkdown = (text: string) => {
  if (!text) return '';
  
  // 先处理换行，避免影响其他格式
  let formatted = text.replace(/\n/g, '<br>');
  
  // 处理完整的粗体标记 **text**
  formatted = formatted.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
  
  // 处理完整的斜体标记 *text*
  formatted = formatted.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g, '<em>$1</em>');
  
  // 处理标题
  formatted = formatted.replace(/### (.*)/g, '<h3>$1</h3>');
  formatted = formatted.replace(/## (.*)/g, '<h2>$1</h2>');
  formatted = formatted.replace(/# (.*)/g, '<h1>$1</h1>');
  
  // 处理高亮显示
  formatted = formatted.replace(/▶ (.*)/g, '<div class="highlight">▶ $1</div>');
  
  return formatted;
};

// 滚动到底部
const scrollToBottom = () => {
  if (chatMessagesRef.value) {
    chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight;
  }
};

// 预览图片
const previewImage = (imageUrl?: string) => {
  if (imageUrl) {
    previewImageUrl.value = imageUrl;
    showImagePreview.value = true;
  }
};

// 检查是否为移动端
const checkIfMobile = () => {
  const isMobileDevice = window.innerWidth <= 768;
  isMobile.value = isMobileDevice;
};

// 监听窗口大小变化
onMounted(() => {
  checkIfMobile();
  window.addEventListener('resize', checkIfMobile);
  
  // 从路由参数获取题目信息（如果有）
  const route = router.currentRoute.value;
  if (route.query.imageUrl) {
    pendingImage.value = route.query.imageUrl as string;
  }
  if (route.query.text) {
    inputText.value = route.query.text as string;
  }
  
  // 加载对话历史
  aiSolverStore.loadFromLocalStorage();
});

onUnmounted(() => {
  window.removeEventListener('resize', checkIfMobile);
  // 确保关闭相机
  if (videoElement.value && videoElement.value.srcObject) {
    const stream = videoElement.value.srcObject as MediaStream;
    const tracks = stream.getTracks();
    tracks.forEach(track => track.stop());
  }
});
</script>

<style lang="scss" scoped>
.ai-chat-view {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.chat-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 20px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 10;

  h1 {
    margin: 0;
    margin-left: 20px;
    font-size: 18px;
    color: #333;
  }

  .header-actions {
    display: flex;
    gap: 10px;
  }
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-messages {
    flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #f9f9f9;

  .message-item {
    display: flex;
    margin-bottom: 20px;
    align-items: flex-start;

    &.user {
      flex-direction: row-reverse;

      .message-content {
        margin-right: 12px;
        margin-left: 0;
      }
    }

    &.ai {
      .message-content {
        margin-left: 12px;
        margin-right: 0;
      }
    }

    .message-avatar {
      flex-shrink: 0;
      width: 40px;
      height: 40px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;

      .user-avatar {
        background-color: #1890ff;
        color: white;
        width: 100%;
        height: 100%;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .ai-avatar {
        background-color: #52c41a;
        color: white;
        width: 100%;
        height: 100%;
        border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
      }
    }

    .message-content {
      max-width: 70%;
      min-width: 200px;

      .user-message,
      .ai-message {
        background-color: #fff;
        border-radius: 12px;
        padding: 12px 16px;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        word-wrap: break-word;

        .message-image {
          margin-bottom: 8px;

          img {
        max-width: 100%;
            max-height: 200px;
            border-radius: 8px;
        cursor: pointer;
        transition: transform 0.3s ease;

        &:hover {
          transform: scale(1.02);
        }
      }
    }

        .message-text {
          line-height: 1.6;
          color: #333;

          p {
            margin: 0;
          }
        }

        .typing-message {
          line-height: 1.6;
          color: #333;
          
          .streaming-message {
            display: inline;
            
            h1, h2, h3 {
              margin: 10px 0 5px 0;
              font-weight: bold;
            }
            
            h1 { font-size: 1.2em; }
            h2 { font-size: 1.1em; }
            h3 { font-size: 1.05em; }
            
            strong {
              font-weight: bold;
              color: #1890ff;
            }
            
            em {
              font-style: italic;
              color: #52c41a;
            }
            
            .highlight {
              background-color: #f0f8ff;
              padding: 8px 12px;
              border-left: 4px solid #1890ff;
              margin: 8px 0;
              border-radius: 4px;
              font-weight: 500;
            }
          }
          
          .typing-cursor {
            display: inline-block;
            animation: blink 1s infinite;
            margin-left: 2px;
          }
        }

        .static-message {
          line-height: 1.6;
          color: #333;
          
          h1, h2, h3 {
            margin: 10px 0 5px 0;
            font-weight: bold;
          }
          
          h1 { font-size: 1.2em; }
          h2 { font-size: 1.1em; }
          h3 { font-size: 1.05em; }
          
          strong {
            font-weight: bold;
            color: #1890ff;
          }
          
          em {
            font-style: italic;
            color: #52c41a;
          }
          
          .highlight {
            background-color: #f0f8ff;
            padding: 8px 12px;
            border-left: 4px solid #1890ff;
            margin: 8px 0;
            border-radius: 4px;
            font-weight: 500;
          }
        }

        .loading-message {
          display: flex;
          align-items: center;
          color: #666;

          .el-icon {
            margin-right: 8px;
          }
        }
      }

      .user-message {
        background-color: #1890ff;
        color: white;

        .message-text p {
          color: white;
        }
      }
    }
  }
}

.chat-input {
  background-color: #fff;
  border-top: 1px solid #e8e8e8;
    padding: 15px 20px;

  .input-toolbar {
    display: flex;
    gap: 10px;
      margin-bottom: 10px;
    }

  .input-area {
      display: flex;
      gap: 10px;
    align-items: flex-end;

    .message-input {
      flex: 1;
    }

    .send-button {
      height: 40px;
      padding: 0 20px;
    }
  }
}

.camera-modal-content {
  display: flex;
  justify-content: center;
}

.camera-feed-container {
  width: 100%;
  max-width: 500px;
  aspect-ratio: 4/3;
  overflow: hidden;
  background-color: #000;
  border-radius: 8px;
}

.camera-feed-container video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.preview-image {
  max-width: 100%;
  max-height: 80vh;
}

// 响应式设计
@media (max-width: 768px) {
  .chat-messages {
    padding: 10px;

    .message-item {
      .message-content {
        max-width: 85%;
        min-width: 150px;
      }
    }
  }

  .chat-input {
    padding: 10px 15px;

    .input-area {
      flex-direction: column;
      gap: 10px;

      .send-button {
        width: 100%;
      }
    }
  }

  .camera-feed-container {
    width: 100%;
    aspect-ratio: 9/16; // 适配手机屏幕比例
  }
}

@keyframes blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0; }
}
</style>